package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.User;
import com.heima.search.dto.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1. 通过用户的id和关键词查询
        ApUserSearch apUserSearch = mongoTemplate.findOne(Query.query(
                Criteria.where("userId")
                        .is(userId)
                        .and("keyword").is(keyword)), ApUserSearch.class);

        //2. 如果查询到了历史记录则更新创建时间即可
        if(null != apUserSearch){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return; //一定要添加retuen
        }

        //3. 如果没有查询到则查询当前用户的所有的历史记录
        List<ApUserSearch> list = mongoTemplate.find(
                Query.query(
                        Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                ApUserSearch.class);

        //4. 判断历史记录是否为空如果不为空则判断是否=10,如果不等则直接插入数据 如果等则更新最老的记录
        apUserSearch = new ApUserSearch();
        apUserSearch.setCreatedTime(new Date());
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);

        if(null == list || list.size() < 10){
            mongoTemplate.save(apUserSearch);
        }else{
            ApUserSearch last = list.get(list.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(last.getId())), apUserSearch);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        User user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Query query = Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索历史
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if(null == historySearchDto || StringUtils.isEmpty(historySearchDto.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        User user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        Query query = Query.query(Criteria.where("userId").is(user.getId()).and("id").is(historySearchDto.getId()));
        DeleteResult deleteResult = mongoTemplate.remove(query, ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
